package service

import (
	"UserApp/api"
	"UserApp/biz"
	"github.com/gin-gonic/gin"
)

type userService struct {
	uc *biz.UserUseCase
}

func ProviderUserService(uc *biz.UserUseCase) api.UserService {
	return &userService{uc: uc}
}

var _ api.UserService = (*userService)(nil)

func (u *userService)CreateUser(ctx *gin.Context, r *api.CreateUserReq) (*api.UserRes, error) {
	//DTO->DO, 调用biz相应接口
	user, err := u.uc.Create(ctx, biz.User{
		Name: r.Name,
		Addr: r.Addr,
	})

	if err != nil {
		return nil, err
	}

	//DO->DTO
	return &api.UserRes{ID: user.Id, Name: user.Name, Addr: user.Addr}, nil
}

func (u *userService)GetUser(ctx *gin.Context, r *api.GetUserReq) (*api.UserRes, error) {
	user, err := u.uc.Get(ctx, int64(r.ID))

	if err != nil {
		return nil, err
	}

	return &api.UserRes{ID:user.Id, Name: user.Name, Addr: user.Addr}, nil
}

func (u *userService)UpdateUser(ctx *gin.Context, r *api.UpdateUserReq) (*api.UserRes, error) {
	user, err := u.uc.Update(ctx, biz.User{Id: int64(r.ID), Addr: r.Addr, Name: r.Name})

	if err != nil {
		return nil, err
	}

	return &api.UserRes{ID: user.Id, Name: user.Name, Addr: user.Addr}, nil
}

func (u *userService)DeleteUser(ctx *gin.Context, r *api.DeleteUserReq) (*api.UserRes, error) {
	user, err := u.uc.Delete(ctx, r.ID)

	if err != nil {
		return nil, err
	}

	return &api.UserRes{ID: user.Id, Name: user.Name, Addr: user.Addr}, nil
}
